<template>
	<view class="padding-bt-100 mainPage" style="padding-top: 0">
		<view class="padding padding-bottom-xl">
			<view class="address padding bg-white radius-xl margin-bottom" @click="toUrl('/pages/user/address/list?pageType=order')">
				<view class="info">
					<view class="username margin-bottom-xs" v-if="address.id">
						<text class="text-bold text-black">{{ address.nickname }}</text>
						<text class="padding-left">{{ address.phone }}</text>
					</view>
					<view v-if="address.address_name" class="detail text-sm text-gray">
						{{ address.address_name}}
					</view>
          <view v-if="address.address" class="detail text-sm text-gray">
            {{ address.address}}
          </view>
          <view v-if="!address.longitude || !address.latitude" class="detail text-sm text-gray">
            请选择地址
          </view>
        </view>
				<view class="more">
					<text class="cuIcon-right text-bold"></text>
				</view>
			</view>
			<view class="padding bg-white radius-xl margin-bottom">
				<view class="project-list padding-bottom-xs">
					<view class="item radius-lg padding-tb"
					:class="projects.length - 1 != index ? 'solid-bottom' : ''"
					v-for="(item,index) in projects" :key="index">
						<image :src="item.image" mode="heightFix" class="img" style="margin-right: 16rpx"></image>
						<view class="probox">
							<view class="title text-bold text-black margin-bottom-xs">
								<text>{{item.name}}</text>
								<view class="text-sm text-right text-red">
									<text class="text-bold">¥</text>
									<text class="text-lg text-bold">{{item.label_price || item.price }} {{ item.unit ? '/' + item.unit : '' }}</text>
								</view>
							</view>
							<view class="text-cut text-gray margin-bottom-sm text-sm">{{item.description }}</view>
							<view class="price flex flex-wrap">
								<view class="time basis-sm text-sm">
									<text class="cuIcon-timefill text-lg themeColor" v-if="item.duration"></text>
                  <text class="padding-left-mn" v-if="item.duration">{{item.duration }}分钟</text>
								</view>
								<view class="basis-lg text-right liji">
									<u-number-box
										button-size="20"
										v-model="item.num"
										min="1"
										style="float: right;">
									</u-number-box>
								</view>
							</view>
						</view>
					</view>
				</view>

				<view class="servicePartner grid col-2 margin-bottom" v-if="partnerInfo.id">
					<view class="">阿姨</view>
					<view class="text-right crow">
						<view class="cu-avatar sm round margin-left f-s" :style="{backgroundImage: 'url('+partnerInfo.image+')'}"></view>
						<text class="padding-lr-sm">{{partnerInfo.nickname}}</text>
					</view>
				</view>
<!--        <view class="servicePartner grid col-2 margin-bottom">-->
<!--          <view class="" style="width: 200rpx">阿姨位置</view>-->
<!--          <view class="text-right crow" style="flex-grow: 1" @click="openMap">-->
<!--            <div style="flex-grow: 1">-->
<!--              <div v-if="partnerInfo.address_name">{{partnerInfo.address_name || ''}}</div>-->
<!--              <div>{{partnerInfo.address || ''}}</div>-->
<!--            </div>-->
<!--          </view>-->
<!--        </view>-->
				<view class="serviceTime grid col-2">
					<view class="">服务时间</view>
					<view class="text-right" @click="toChangeServeTime()">
						<text class="padding-left-sm themeColor">{{ serveTime || '请选择服务时间'}}</text>
						<text class="cuIcon-right"></text>
					</view>
				</view>
			</view>

			<!-- 出行方式 -->
<!--			<view class="travel padding bg-white radius-xl margin-bottom">-->
<!--				<view class="grid col-2">-->
<!--					<view class="text-black text-bold">出行方式</view>-->
<!--					<view class="text-right" @click="toChangeTravel()">-->
<!--						<text class="themeColor">{{ selectTravel.label }}</text>-->
<!--						<text class="cuIcon-right"></text>-->
<!--					</view>-->
<!--				</view>-->
<!--				<view class="tips padding-sm" v-if="selectTravel.value">-->
<!--          全程共{{ totalkm }}km，{{ selectTravel.label }}收取来回车费，起步{{ selectTravel.start_price }}元/{{ selectTravel.start_km }}km,超出1km,收取{{ selectTravel.over_km_price }}元-->
<!--				</view>-->
<!--				<view class="fare">-->
<!--					<label>车费</label>-->
<!--					<view class="text-red margin-right-xs text-bold">￥{{ totalPrice }}</view>-->
<!--				</view>-->
<!--			</view>-->

<!--			<view class="coupon padding bg-white radius-lg margin-tb"  @click="toSetCouponShow" v-if="couponList">-->
<!--				<text>选择优惠券</text>-->
<!--				<view class="selected" @click="toSetCouponShow">-->
<!--					<text class="text-orange">-￥20.50</text>-->
<!--					<text class="cuIcon-right"></text>-->
<!--				</view>-->
<!--			</view>-->

			<view class="remark padding bg-white radius-xl">
				<view>
					<textarea maxlength="255"  placeholder="在此输入备注信息" v-model="form.remark"></textarea>
				</view>
			</view>
		</view>

		<view class="cu-bar bg-white tabbar shop foot grid col-2">
			<view class="padding-left">
				合计：<text class="text-red text-lg text-bold">¥{{ amount || '0.00' }}</text>
			</view>
			<view class="reservation text-right padding-right">
				<button class="cu-btn round china-btn-bg " @click="getOrderData('post')">
					<text class="padding-lr-xl">立即下单</text>
				</button>
			</view>
		</view>

    <u-select
        cancel-color="#0ab27d"
        confirm-color="#0ab27d"
        mode="single-column" v-model="travelShow" :list="travelsList" @confirm="pickerPopup"></u-select>
<!--		<serviveTime :show="serviceTimeShow" :partnerId="form.partnerId" @serviceTimePopup="serviceTimePopup" v-if="serviceTimeShow"/>-->

		<payType
        ref="payTypeRef"
      :orderData="orderData"
			@payCallBack="payCallBack"
			:referParams="form"
			source='partner'/>

		<myCoupon :show="couponShow" :list="couponList" @couponPopup="couponPopup"/>
    <u-popup v-model="dateShow" mode="bottom" border-radius="14">
      <div class="calendar-picker">
        <div class="calendar-header">
          <div class="calendar-title">选择服务时间</div>
          <div class="calendar-actions">
            <span class="cancel-btn" @click="cancelDate">取消</span>
            <span class="confirm-btn" @click="confirmDate">确定</span>
          </div>
        </div>
        
        <!-- 日历部分 -->
        <div class="calendar-section">
          <div class="calendar-nav">
            <div class="nav-btn" v-if="canShowPrevMonth" @click="prevMonth">
              <text class="cuIcon-back"></text>
            </div>
            <div class="nav-btn-placeholder" v-else></div>
            <div class="current-month">{{ currentYear }}年{{ currentMonth }}月</div>
            <div class="" @click="goToCurrentMonth" v-if="!isCurrentMonth" title="回到当月">
              <text class="cuIcon-refresh"></text>
              <span class="today-text">今天</span>
            </div>
            <div class="nav-btn" @click="nextMonth">
              <text class="cuIcon-right"></text>
            </div>
          </div>
          
          <div class="calendar-weekdays">
            <div class="weekday" v-for="day in weekdays" :key="day">{{ day }}</div>
          </div>
          
          <div class="calendar-days">
            <div 
              v-for="(day, index) in calendarDays.filter(day => day.day)" 
              :key="index"
              :class="[
                'calendar-day',
                day.isCurrentMonth ? '' : 'other-month',
                day.isToday ? 'today' : '',
                day.isSelected ? 'selected' : '',
                day.isDisabled ? 'disabled' : '',
                day.hasTimeSlots ? 'has-slots' : ''
              ]"
              @click="selectDate(day)"
            >
              <span class="day-number">{{ day.day }}</span>
              <span v-if="day.hasTimeSlots" class="time-indicator"></span>
            </div>
          </div>
        </div>
        
        <!-- 时间段选择部分 -->
        <div class="time-section">
          <div class="time-section-title">
            <span>{{ selectedDateInfo ? selectedDateInfo.dateText : '请选择日期' }}</span>
            <span class="time-slots-count">{{ availableTimeSlotsCount }}个时段可选</span>
          </div>
          <div class="time-slots">
            <div 
              v-for="(slot, index) in availableTimeSlots" 
              :key="index"
              :class="[
                'time-slot',
                slot.time === activeTime ? 'active' : '',
                slot.disabled ? 'disabled' : ''
              ]"
              @click="slot.disabled ? null : selectTimeSlot(slot)"
            >
              <span>{{ slot.time }}</span>
            </div>
          </div>
        </div>
      </div>
    </u-popup>

		<Loading v-if="pageLoading"/>
	</view>
</template>

<script>
	import serviveTime from './modules/serviceTime.vue'; // 服务时间
	import payType from '@/components/payType/payType.vue'; // 服务时间
	import myCoupon from '@/components/myCoupon/myCoupon.vue'; // 优惠券
  import dayjs from 'dayjs'
	export default {
		components: {serviveTime,payType,myCoupon},
		data() {
			return {
				pageLoading:false,
				form:{
					partnerId:0,
					addressId:0,
					serviveTime:[],
					remark:'',
					couponId:0
				},
				orderData:{
					pay_amount: 0
				},
				address: {},
        travelName: '',
        travelDesc: '',
        travelsList: [],
				travels: [
				],
				projects: [],//项目信息
				partnerInfo: {},//阿姨信息
				selectTravel: {},//选中出行方式
        serveTime: '',
				travelShow:false,//出行方式弹出层
				serviceTimeShow:false,//服务时间弹出层
				couponShow:false,//优惠券弹出层
				couponList:[
					{
						reduce_price:'10.50',
						name:'满减券',
						min_price:'200',
						end_time:'2023-09-18',
						is_usable:10,
						user_coupon_id:1
					},
					{
						reduce_price:'20.50',
						name:'满减券',
						min_price:'500',
						end_time:'2023-09-18',
						is_usable:20,
						user_coupon_id:2
					}
				],
        dateShow: false,
        activeDay: dayjs().format('YYYY-MM-DD'),
        activeTime: '',
        userInfo: {},
        // 日历相关数据
        currentYear: dayjs().year(),
        currentMonth: dayjs().month() + 1,
        weekdays: ['一', '二', '三', '四', '五', '六', '日'],
        calendarDays: [],
        selectedDateInfo: null,
        availableTimeSlots: [],
        activeTimeSlots: [],
        // 服务时间数据
        serviceTimeData: {}
			};
		},
		onLoad(options) {
      let that = this
      uni.$on('address',(res)=>{
        that.address = res
      })
      this.form.partnerId = options.partnerId;
      this.projects = JSON.parse(options.projects);
      console.log(this.projects)
      for (let i = 0; i < this.projects.length; i++) {
        const project = this.projects[i];
        console.log('project', project)
        this.$http.getProjectDetail({
          id: project.id
        }).then(res => {
          console.log(res, '详情')
          this.projects.splice(i, 1, {
            ...res,
            num: project.num,
            orderDetails: undefined
          })
          console.log(this.projects)
        })
      }

      if (options.partnerId) {
        this.$http.getTechnicianDetail({
          id: options.partnerId
        }).then(res => {
          this.partnerInfo = res
        })
        this.$http.getTravelModeList().then(res => {
          this.travelsList = res.map(item => {
            return {
              label: item.name,
              value: item.id,
              ...item
            }
          })
          if (this.travelsList.length) {
            this.selectTravel = {
              label: this.travelsList[0].name,
              value: this.travelsList[0].id,
              ...this.travelsList[0],
            }
          }
        })
      }
      // // 根据当前时间计算日期 如果超过晚上8点 则默认选择明天 并且仅展示明天的列表
      // const hour = dayjs().hour()
      // if (hour >= 20) {
      //   this.activeDay = dayjs().add(1, 'day').format('YYYY-MM-DD')
      //   this.dayList = [
      //     {id: 0, day: `明天${dayjs().add(1, 'day').format('MM月DD日')}`, value: dayjs().add(1, 'day').format('YYYY-MM-DD')},
      //     {id: 1, day: `后天${dayjs().add(2, 'day').format('MM月DD日')}`, value: dayjs().add(2, 'day').format('YYYY-MM-DD')},
      //   ]
      // } else {
      //   this.activeDay = dayjs().format('YYYY-MM-DD')
      //   this.dayList = [
      //     {id: 0, day: `今天${dayjs().format('MM月DD日')}`, value: dayjs().format('YYYY-MM-DD')},
      //   ]
      // }

      // 初始化日历
      this.generateCalendar()
      
      // 生成固定时间段数据
      this.generateFixedTimeSlots()
      
      // 设置默认选中今天
      const now = dayjs();
      this.activeDay = now.format('YYYY-MM-DD')
      this.selectedDateInfo = {
        dateText: now.format('MM月DD日'),
        date: this.activeDay
      }
      this.generateTimeSlots(this.activeDay)
		},
    onShow() {
      this.userInfo = uni.getStorageSync('userInfo') || {}
      if (!this.userInfo.id) {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        })
        setTimeout(() => {
          uni.navigateTo({
            url: '/pages/login/login'
          })
        }, 500)
        return
      }
      // 获取默认地址
      if (!this.address.id) {
        this.$http.getDefaultAddress({
          member_id: uni.getStorageSync('userInfo').id
        }).then(res => {
          if (res) {
            this.address = res
          }
        })
      }
    },
		methods:{
      // 打开地图
      openMap() {
        const latitude = parseFloat(this.partnerInfo.latitude);
        const longitude = parseFloat(this.partnerInfo.longitude);
        const address = this.partnerInfo.address;
        const address_name = this.partnerInfo.address_name;

        uni.openLocation({
          name: address_name, // 位置名
          latitude: latitude, // 纬度
          longitude: longitude, // 经度
          address: address, // 地址的详细描述
          success() {
            console.log('地图打开成功');
          },
          fail(error) {
            console.error('地图打开失败', error);
          }
        });
      },
      getOrderData(){
        const userInfo = uni.getStorageSync('userInfo') || {}
        if (!userInfo.id) {
          uni.showToast({
            title: '请先登录',
            icon: 'none'
          })
          return;
        }
        if (!this.address.id) {
          uni.showToast({
            title: '请选择地址',
            icon: 'none'
          })
          return
        }
        if (this.projects.every(item => item.num === 0)) {
          uni.showToast({
            title: '请选择项目',
            icon: 'none'
          })
          return
        }
        // if (!this.selectTravel.value) {
        //   uni.showToast({
        //     title: '请选择出行方式',
        //     icon: 'none'
        //   })
        //   return
        // }
        if (!this.serveTime) {
          uni.showToast({
            title: '请选择服务时间',
            icon: 'none'
          })
          return
        }
        // if (!this.partnerInfo.longitude || !this.partnerInfo.latitude) {
        //   uni.showToast({
        //     title: '阿姨地址不正确',
        //     icon: 'none'
        //   })
        //   return
        // }
        this.orderData.pay_amount = this.amount
        this.$refs.payTypeRef.open()
			},
			async payCallBack(pay_type){
        uni.showLoading({
          title: '请等待'
        })
        const params = {
          address: JSON.stringify(this.address),
          staff_address: JSON.stringify({
            address: this.partnerInfo.address,
            address_name: this.partnerInfo.address_name,
            latitude: this.partnerInfo.latitude,
            longitude: this.partnerInfo.longitude,
            phone: this.partnerInfo.phone,
            nickname: this.partnerInfo.nickname
          }),
          staff_id: this.form.partnerId || 0,
          member_id: uni.getStorageSync('userInfo').id,
          projects: this.projects,
          travel_mode_id: this.selectTravel.value || 0,
          travel_mode_name: this.selectTravel.label,
          travel_mode_fee: this.totalPrice || 0,
          start_time: this.serveTime,
          end_time: this.serveTime,
          remark: this.form.remark,
          pay_amount: this.amount,
          pay_type: pay_type,
          totalkm: this.totalkm || 0,
          body: '服务订单'
        }
        const orderRes = await this.$http.createOrder({
          ...params
        })
        if (this.amount === 0) {
          uni.redirectTo({
            url: '/pages/order/payment/payment'
          })
        } else {
          this.wxPay(orderRes)
        }

			},
      wxPay(orderRes) {
        const { order_no } = orderRes
        this.$http.payment({
          order_no
        }).then(res => {
          // 小程序
          wx.requestPayment({
            timeStamp: res.timestamp,
            nonceStr: res.nonce_str,
            package: res.package,
            signType: res.signType,
            paySign: res.paySign,
            success () {
              uni.redirectTo({
                url: '/pages/order/payment/payment'
              })
            },
            fail (res) {
              uni.reLaunch({
                url: '/pages/order/list'
              })
            }
          })
        })
      },
      wxH5Pay(orderRes) {
        const { order_no } = orderRes
        this.$http.paymentH5({
          order_no
        }).then(res => {
          WeixinJSBridge.invoke('getBrandWCPayRequest', {
            appId: res.appid,
            timeStamp: res.timestamp,
            nonceStr: res.nonce_str,
            package: res.package,
            signType: res.signType,
            paySign: res.paySign,
          },
          function(res) {
            console.log('下单成功',res)
            if (res.err_msg == "get_brand_wcpay_request:ok") {
              // 使用以上方式判断前端返回,微信团队郑重提示：
              //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
              uni.redirectTo({
                url: '/pages/order/payment/payment'
              })
            } else {
              uni.reLaunch({
                url: '/pages/order/list'
              })
            }
          });})
      },
			serviceTimePopup(e){
				if(e.type=='confirm'){
					this.form.serviveTime = e.data;
					this.getOrderData('get');
				}
				this.serviceTimeShow = false
			},
			pickerPopup(e){
        console.log(e)
        let selectTravel = e[0];
        this.selectTravel = this.travelsList.find(item => item.value === selectTravel.value)
				this.travelShow = false;
			},
			couponPopup(e){
				this.form.couponId = e.data;
				this.couponShow = false;
				this.getOrderData('get');
			},
			toChangeTravel(){
				this.travelShow = true;
			},
			toChangeServeTime(){
        // 直接生成固定的时间段，不需要调用后端接口
        this.generateFixedTimeSlots()
        this.dateShow = true
        
        // 如果已有选择的时间，设置选中状态
        if (this.serveTime) {
          const [date, time] = this.serveTime.split(' ')
          this.activeDay = date
          this.activeTime = time
          // 设置日历到对应月份
          const dateObj = dayjs(date)
          this.currentYear = dateObj.year()
          this.currentMonth = dateObj.month() + 1
          this.generateCalendar()
          
          // 设置选中日期信息
          this.selectedDateInfo = {
            dateText: dayjs(date).format('MM月DD日'),
            date: date
          }
          
          // 生成对应日期的时间段
          this.generateTimeSlots(date)
        } else {
          // 如果没有选择过，默认选择今天
          const now = dayjs();
          this.activeDay = now.format('YYYY-MM-DD')
          this.selectedDateInfo = {
            dateText: now.format('MM月DD日'),
            date: this.activeDay
          }
          this.generateTimeSlots(this.activeDay)
        }
			},
			toSetCouponShow(){
				this.couponShow = true;
			},
      toUrl(page) {
        uni.navigateTo({
          url:page
        })
      },

      Rad(d) { //根据经纬度判断距离
        return d * Math.PI / 180.0;
      },
      getDistance(lat1, lng1, lat2, lng2) {
        console.log('lat1, lng1, lat2, lng2',lat1, lng1, lat2, lng2)
        if (!lat1 || !lng1 || !lat2 || !lng2) {
          return 0
        }
        if (lat1 == lat2 && lng1 == lng2) {
          return 0;
        }
        // lat1用户的纬度
        // lng1用户的经度
        // lat2阿姨的纬度
        // lng2阿姨的经度
        var radLat1 = this.Rad(lat1);
        var radLat2 = this.Rad(lat2);
        var a = radLat1 - radLat2;
        var b = this.Rad(lng1) - this.Rad(lng2);
        var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
        s = s * 6378.137;
        s = Math.round(s * 10000) / 10000;
        s = s * 2
        s = s.toFixed(2)
        console.log('经纬度计算的距离:' + s)
        return parseFloat(s)
      },

      confirmDate() {
        if (!this.activeDay) {
          uni.showToast({
            title: '请选择日期',
            icon: 'none'
          })
          return
        }
        if (!this.activeTime) {
          uni.showToast({
            title: '请选择时间',
            icon: 'none'
          })
          return
        }
        this.dateShow = false
        this.serveTime = `${this.activeDay} ${this.activeTime}`
      },
      cancelDate() {
        this.dateShow = false
      },
      prevMonth() {
        // 检查是否可以切换到上个月
        if (!this.canShowPrevMonth) {
          return;
        }
        
        this.currentMonth--;
        if (this.currentMonth < 1) {
          this.currentMonth = 12;
          this.currentYear--;
        }
        this.generateCalendar();
      },
      nextMonth() {
        this.currentMonth++;
        if (this.currentMonth > 12) {
          this.currentMonth = 1;
          this.currentYear++;
        }
        this.generateCalendar();
      },
      goToCurrentMonth() {
        const now = dayjs();
        this.currentYear = now.year();
        this.currentMonth = now.month() + 1;
        this.generateCalendar();
        
        // 可选：同时选中今天的日期
        const today = now.format('YYYY-MM-DD');
        this.activeDay = today;
        this.selectedDateInfo = {
          dateText: now.format('MM月DD日'),
          date: today
        };
        this.generateTimeSlots(today);
      },
      generateCalendar() {
        this.calendarDays = [];
        
        // 获取当月第一天是周几（0=周日，1=周一，...，6=周六）
        const firstDayOfWeek = dayjs(`${this.currentYear}-${this.currentMonth}-01`).day();
        // 转换为周一为1的格式（1=周一，2=周二，...，7=周日）
        const firstDay = firstDayOfWeek === 0 ? 7 : firstDayOfWeek;
        
        // 获取当月的天数
        const daysInMonth = dayjs(`${this.currentYear}-${this.currentMonth}`).daysInMonth();
        
        console.log(`生成日历: ${this.currentYear}年${this.currentMonth}月`);
        console.log(`第一天是周${firstDayOfWeek}，转换后是${firstDay}`);
        console.log(`当月天数: ${daysInMonth}`);
        
        // 填充月初空白日期（周一为第一列，所以需要填充 firstDay-1 个空白）
        console.log(`填充月初空白: ${firstDay - 1} 个`);
        for (let i = 0; i < firstDay - 1; i++) {
          this.calendarDays.push({
            day: '',
            isCurrentMonth: false,
            isToday: false,
            isSelected: false,
            isDisabled: true,
            hasTimeSlots: false
          });
        }
        
        // 填充当月日期
        console.log(`填充当月日期: 1 到 ${daysInMonth}`);
        for (let day = 1; day <= daysInMonth; day++) {
          const date = dayjs(`${this.currentYear}-${this.currentMonth}-${day}`).format('YYYY-MM-DD');
          const now = dayjs();
          const isToday = date === now.format('YYYY-MM-DD');
          const isSelected = date === this.activeDay;
          const isDisabled = !this.isDateAvailable(date);
          const hasTimeSlots = this.isTimeSlotAvailable(date);
          
          this.calendarDays.push({
            day: day,
            date: date,
            isCurrentMonth: true,
            isToday: isToday,
            isSelected: isSelected,
            isDisabled: isDisabled,
            hasTimeSlots: hasTimeSlots
          });
        }
        
        // 填充月末空白日期，确保总数为42（6行7列）
        const totalDays = this.calendarDays.length;
        const remainingDays = 42 - totalDays;
        console.log(`填充月末空白: ${remainingDays} 个，总计: ${totalDays + remainingDays}`);
        for (let i = 0; i < remainingDays; i++) {
          this.calendarDays.push({
            day: '',
            isCurrentMonth: false,
            isToday: false,
            isSelected: false,
            isDisabled: true,
            hasTimeSlots: false
          });
        }
      },
      isDateAvailable(date) {
        // 检查日期是否可用（不能是过去的日期）
        const now = dayjs();
        const today = now.format('YYYY-MM-DD');
        return date >= today;
      },
      isTimeSlotAvailable(date) {
        // 检查该日期是否有可用时间段
        // 现在所有未来日期都有固定的时间段
        if (!this.serviceTimeData || !Array.isArray(this.serviceTimeData)) {
          return false;
        }
        
        const dayData = this.serviceTimeData.find(item => item.value === date);
        return dayData && dayData.children && dayData.children.length > 0;
      },
      selectDate(day) {
        if (day.isDisabled || !day.isCurrentMonth) return;
        
        this.activeDay = day.date;
        this.selectedDateInfo = {
          dateText: dayjs(day.date).format('MM月DD日'),
          date: day.date
        };
        
        // 更新选中状态
        this.calendarDays.forEach(d => {
          d.isSelected = d.date === day.date;
        });
        
        // 生成时间段但不重置已选择的时间
        this.generateTimeSlots(day.date);
      },
      generateTimeSlots(selectedDate) {
        this.availableTimeSlots = [];
        
        if (!this.serviceTimeData || !Array.isArray(this.serviceTimeData)) {
          return;
        }
        
        if (selectedDate) {
          const dayData = this.serviceTimeData.find(item => item.value === selectedDate);
          if (dayData && dayData.children) {
            // 过滤时间段，只显示当前时间之后的时间段
            this.availableTimeSlots = this.filterTimeSlots(dayData.children, selectedDate);
          }
        } else {
          // 如果没有选择日期，显示今天的时间段
          const now = dayjs();
          const today = now.format('YYYY-MM-DD');
          const dayData = this.serviceTimeData.find(item => item.value === today);
          if (dayData && dayData.children) {
            this.availableTimeSlots = this.filterTimeSlots(dayData.children, today);
          }
        }
      },
      selectTimeSlot(slot) {
        // 如果时间段被禁用，不允许选择
        if (slot.disabled) {
          return;
        }
        this.activeTime = slot.time;
        // 不重置selectedDateInfo，保持日期选择状态
      },
      filterTimeSlots(timeSlots, selectedDate) {
        const now = dayjs();
        const selectedDateTime = dayjs(selectedDate);
        
        // 如果是今天，需要标记已经过去的时间段为禁用
        if (selectedDateTime.isSame(now, 'day')) {
          const currentHour = now.hour();
          const currentMinute = now.minute();
          
          return timeSlots.map(slot => {
            const [hour] = slot.time.split(':').map(Number);
            // 如果时间段的小时数小于当前小时，或者等于当前小时但已经过了30分钟，则禁用
            const isDisabled = hour < currentHour || (hour === currentHour && currentMinute >= 30);
            return {
              ...slot,
              disabled: isDisabled
            };
          });
        }
        
        // 如果不是今天，所有时间段都可用
        return timeSlots.map(slot => ({
          ...slot,
          disabled: false
        }));
      },
      generateFixedTimeSlots() {
        // 生成未来30天的固定时间段数据
        this.serviceTimeData = [];
        const now = dayjs();
        
        for (let i = 0; i < 30; i++) {
          const date = now.add(i, 'day').format('YYYY-MM-DD');
          const dayText = i === 0 ? '今天' : i === 1 ? '明天' : i === 2 ? '后天' : now.add(i, 'day').format('MM月DD日');
          
          // 生成9点到20点的时间段，每小时一个
          const timeSlots = [];
          for (let hour = 9; hour <= 20; hour++) {
            const time = `${hour.toString().padStart(2, '0')}:00`;
            timeSlots.push({
              time: time,
              status: 1, // 1表示可用
              statusText: ''
            });
          }
          
          this.serviceTimeData.push({
            day: dayText,
            value: date,
            children: timeSlots
          });
        }
        
        // 重新生成日历
        this.generateCalendar();
      },
		},
    computed: {
      totalkm() {
        // 根据address中的坐标
        return this.getDistance(this.address.latitude, this.address.longitude, this.partnerInfo.latitude, this.partnerInfo.longitude)
      },
      totalPrice() {
        let price = 0
        let totalkm = this.totalkm
        if (!totalkm) return 0
        if (this.selectTravel.value) {
          price+=Number(this.selectTravel.start_price)
          if (totalkm > this.selectTravel.start_km) {
            price += (totalkm - this.selectTravel.start_km) * Number(this.selectTravel.over_km_price)
          }
        }
        return price.toFixed(2)
      },
      addressText() {
        return this.address.province + this.address.city + this.address.area + this.address.address || '请选择地址'
      },
      amount() {
        let val = this.projects.reduce((total, item) => {
          return total + item.price * item.num
        }, 0)
        return val
        // return val + parseFloat(this.totalPrice)
      },
      availableTimeSlotsCount() {
        return this.availableTimeSlots.filter(slot => !slot.disabled).length;
      },
      canShowPrevMonth() {
        const now = dayjs();
        const currentYear = now.year();
        const currentMonth = now.month() + 1;
        
        // 如果当前显示的年月小于等于当前年月，则隐藏上个月按钮
        if (this.currentYear < currentYear) {
          return false;
        }
        if (this.currentYear === currentYear && this.currentMonth <= currentMonth) {
          return false;
        }
        return true;
      },
      isCurrentMonth() {
        const now = dayjs();
        const currentYear = now.year();
        const currentMonth = now.month() + 1;
        
        return this.currentYear === currentYear && this.currentMonth === currentMonth;
      }
    }
	}
</script>

<style lang="less">
.f-s {
  flex-shrink: 0;
  margin-right: 5rpx;
}

// 日历选择器样式
.calendar-picker {
  background-color: #ffffff;
  max-height: 90vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  
  .calendar-header {
    padding: 30rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1rpx solid #f5f5f5;
    
    .calendar-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333333;
    }
    
    .calendar-actions {
      display: flex;
      gap: 30rpx;
      
      .cancel-btn, .confirm-btn {
        font-size: 28rpx;
        padding: 10rpx 20rpx;
        border-radius: 8rpx;
        cursor: pointer;
      }
      
      .cancel-btn {
        color: #666666;
        background-color: #f5f5f5;
      }
      
      .confirm-btn {
        color: #ffffff;
        background-color: #ff6600;
      }
    }
  }
  
  .calendar-section {
    padding: 15rpx;
    flex-shrink: 0;
    
    .calendar-nav {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20rpx;
      
      .nav-btn {
        width: 60rpx;
        height: 60rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: #f5f5f5;
        border-radius: 50%;
        cursor: pointer;
        
        .cuIcon-left, .cuIcon-right {
          font-size: 24rpx;
          color: #666666;
        }
      }
      
      .nav-btn-placeholder {
        width: 60rpx;
        height: 60rpx;
      }
      
      .today-btn {
        background-color: #ff6600 !important;
        border: 2rpx solid #ff6600;
        display: flex;
        align-items: center;
        gap: 8rpx;
        padding: 0 16rpx;
        
        .cuIcon-refresh {
          color: #ffffff !important;
          font-size: 28rpx;
        }
        
        .today-text {
          color: #ffffff !important;
          font-size: 24rpx;
          font-weight: bold;
        }
        
        &:hover {
          background-color: #e55a00 !important;
        }
      }
      
      .current-month {
        font-size: 32rpx;
        font-weight: bold;
        color: #333333;
      }
    }
    
    .calendar-weekdays {
      display: grid;
      grid-template-columns: repeat(7, 1fr);
      margin-bottom: 15rpx;
      
      .weekday {
        text-align: center;
        font-size: 28rpx;
        color: #999999;
        padding: 15rpx 0;
        font-weight: bold;
      }
    }
    
    .calendar-days {
      display: grid;
      grid-template-columns: repeat(7, 1fr);
      gap: 8rpx;
      
      .calendar-day {
        aspect-ratio: 1;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        border-radius: 12rpx;
        position: relative;
        cursor: pointer;
        transition: all 0.3s ease;
        
        .day-number {
          font-size: 28rpx;
          color: #333333;
          font-weight: 500;
        }
        
        .time-indicator {
          position: absolute;
          bottom: 8rpx;
          width: 8rpx;
          height: 8rpx;
          // background-color: #ff6600;
          border-radius: 50%;
        }
        
        &.other-month {
          .day-number {
            color: #cccccc;
          }
        }
        
        &.today {
          background-color: #fff3e0;
          border: 2rpx solid #ff6600;
          
          .day-number {
            color: #333;
            font-weight: bold;
          }
        }
        
        &.selected {
          background-color: #ff6600;
          color: #fff !important;
          .day-number {
            color: #ffffff !important;
            font-weight: bold;
          }
          
          .time-indicator {
            background-color: #ffffff;
          }
        }
        
        &.disabled {
          cursor: not-allowed;
          
          .day-number {
            color: #cccccc;
          }
        }
        
        &.has-slots:not(.disabled) {
          .day-number {
           //  color: #ff6600;
           //  font-weight: bold;
          }
        }
        
        //&:hover:not(.disabled) {
        //  background-color: #ff6600;
        //}
      }
    }
  }
  
  .time-section {
    border-top: 1rpx solid #f5f5f5;
    padding: 20rpx;
    padding-bottom: 50rpx;
    flex: 1;
    display: flex;
    flex-direction: column;
    
    .time-section-title {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20rpx;
      flex-shrink: 0;
      
      span:first-child {
        font-size: 32rpx;
        font-weight: bold;
        color: #333333;
      }
      
      .time-slots-count {
        font-size: 24rpx;
        color: #999999;
      }
    }
    
    .time-slots {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 15rpx;
      flex: 1;
      align-content: start;
      
      .time-slot {
        height: 70rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        border: 2rpx solid #e5e5e5;
        border-radius: 12rpx;
        font-size: 26rpx;
        color: #333333;
        cursor: pointer;
        transition: all 0.3s ease;
        
        &.active {
          background-color: #ff6600;
          color: #ffffff;
          border-color: #ff6600;
        }
        
        &.disabled {
          background-color: #f8f8f8;
          color: #999999;
          border-color: #e5e5e5;
          cursor: not-allowed;
        }
        
        //&:hover:not(.disabled) {
        //  border-color: #ff6600;
        //  color: #ffffff;
        //}
      }
    }
  }
}

// 保留原有的日期选择器样式（兼容性）
.date-picker-content {
  overflow: hidden;
  background-color: #ffffff;
  height: 50vh;
  display: flex;
  flex-direction: column;
  .date-picker-slide {
    flex-shrink: 0;
    display: flex;
    align-items: center;
    background-color: #f8f8f8;
    .date-slide-item {
      font-size: 28rpx;
      color: #333333;
      padding: 20rpx 0;
      text-align: center;
      flex: 1;
      position: relative;
      &.active {
        color: #ff6600;
        background-color: #ffffff;
        &::after {
          content: '';
          position: absolute;
          bottom: 0;
          left: 50%;
          transform: translateX(-50%);
          width: 40rpx;
          height: 4rpx;
          background-color: #ff6600;
          border-radius: 2rpx;
        }
      }
    }
  }
  .date-time-list {
    flex: 1;
    overflow: auto;
    background-color: #ffffff;
    display: grid;
    grid-template-columns: repeat(5, 1fr);
    gap: 20rpx;
    padding: 20rpx 40rpx;
    align-content: start;
    .date-time-item {
      flex-shrink: 0;
      height: 80rpx;
      line-height: 80rpx;
      font-size: 26rpx;
      color: #333333;
      text-align: center;
      width: 100%;
      border-radius: 8rpx;
      border: 1px solid #e5e5e5;
      &.active {
        background-color: #ff6600;
        color: #ffffff;
        border-color: #ff6600;
      }
      &.disabled {
        color: #999999;
        border-color: #e5e5e5;
        background-color: #f8f8f8;
      }
    }
  }
}
.date-picker-title {
  padding: 30rpx;
  background-color: #ffffff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 32rpx;
  color: #333333;
  border-bottom: 1rpx solid #f5f5f5;
  .confirm-text {
    color: #ff6600;
    font-size: 28rpx;
  }
}

.address{
	display: flex;
	justify-content: space-between;
	align-items: center;
}
.project-list{
	.item{
		display: flex;
		align-items: center;
		justify-content: space-between;
		flex-direction: row;
		height: 190upx;
		.img{
			width: 170upx;
			height: 140upx;
			border-radius: 10upx;
		}
		.probox{
			width: 70%;
			.title{
				display: flex;
				justify-content: space-between;
				align-items: baseline;
				.cost{
					width: 125upx;
				}
			}
		}
	}
}
.servicePartner{
	.crow{
		justify-content: flex-end;
	}
}
.goAddAddress{
	margin: auto;
}
.travel{
	.tips {
		background: #efefef;
		border-radius: 10rpx;
		margin-top: 20rpx;
		font-size: 24rpx;
		font-weight: 500;
		color: blcak;
		line-height: 36rpx;
	}

	.fare {
		display: flex;
		align-items: center;
		justify-content: space-between;
		font-size: 28rpx;
		margin-top: 20rpx;
	}
}
.remark{
	textarea{
		height: 100upx;
	}
}
.foot{
	height: 120upx;
}
.coupon{
	font-size: 14px;
	display: flex;
	justify-content: space-between;
	align-items: center;
}
</style>
